package com.zhiyou100.action;

import com.zhiyou100.entity.Student;
import com.zhiyou100.service.StudentService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author yang
 * @className TeacherAction
 * @packageName com.zhiyou100.action
 * @Description TODO 老师 action
 * @date 2020-08-25 19:31
 */
@Controller
@RequestMapping("/student")
public class StudentAction {
    private StudentService studentService;

    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }


    @RequestMapping("/getAll.action")
    public String getAll(Model model) {
        final List<Student> studentList = studentService.getStudentList();
        model.addAttribute("studentList", studentList);

        return "jsp/success";
    }


    /**
     * 文件下载
     *
     * @param request  request
     * @param response response
     * @param fileName 文件名字
     * @return null
     */
    @SneakyThrows
    @RequestMapping("/download.action")
    public String downloads(HttpServletRequest request, HttpServletResponse response, String fileName) {
        // 获取真实路径， 服务器地址
        final String path = request.getServletContext().getRealPath("/files");
        //String fileName = "1598257963665deepin-20Beta-desktop-amd64.iso";

        // 设置 response
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));


        final File file = new File(path, fileName);
        final FileInputStream input = new FileInputStream(file);
        final ServletOutputStream out = response.getOutputStream();

        // 拷贝文件
        FileCopyUtils.copy(input, out);


        return null;
    }


    /**
     * 文件上传
     */
    @RequestMapping("/upload.action")
    public String fileUpload1(
            String sname, String spwd, @RequestParam("sphoto") CommonsMultipartFile fileUpload, Date sbirthday, HttpServletRequest request
    ) {


        // 上传位置保存的位置
        final String path = request.getServletContext().getRealPath("/files");
        final File realPath = new File(path);


        // 防止文件名重复，加上毫秒值
        final String filename =
                System.currentTimeMillis() + fileUpload.getOriginalFilename();


        // 最终的地址
        final File finalPath = new File(realPath, filename);

        // 通过 通过CommonsMultipartFile的方法直接写文件
        try {
            fileUpload.transferTo(finalPath);
        } catch (IOException e) {
            e.printStackTrace();
        }


        final Student student = new Student(sname, spwd, filename, sbirthday);
        final int i = studentService.addStudent(student);

        String message = "添加 " + (i > 0 ? "成功" : "失败！") + "  上传文件成功！！！\n，文件名 " + fileUpload.getOriginalFilename() + " \n 上传的位置 " + realPath.getAbsolutePath() + "  文件的绝对地址" + finalPath.getAbsolutePath();

        request.setAttribute("message", message);

        return "jsp/success";
    }


    /**
     * 自定义一个 日期属性编辑器
     *
     * @param request HttpServletRequest
     * @param binder  binder
     */
    @InitBinder
    public void myDateBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws UnsupportedEncodingException {
        request.setCharacterEncoding("utf-8");
        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

        binder.registerCustomEditor(Date.class, new CustomDateEditor(simpleDateFormat, true));
    }

    @RequestMapping("/deloneByTid.action")
    public String delOneByTid(Integer tid, Model modelAndView) {
        final int i = studentService.deleteStudent(tid);

        String message = i > 0 ? "删除成功" : "删除失败";
        modelAndView.addAttribute("message", message);

        return "jsp/success";

    }

    @RequestMapping("/updateOne.action")
    public String updateOne(Integer sid, String sname, String spwd, @RequestParam("sphoto") CommonsMultipartFile fileUpload, Date sbirthday, HttpServletRequest request
    ) {


        // 上传位置保存的位置
        final String path = request.getServletContext().getRealPath("/files");
        final File realPath = new File(path);


        // 防止文件名重复，加上毫秒值
        final String filename =
                System.currentTimeMillis() + fileUpload.getOriginalFilename();


        // 最终的地址
        final File finalPath = new File(realPath, filename);

        // 通过 通过CommonsMultipartFile的方法直接写文件
        try {
            fileUpload.transferTo(finalPath);
        } catch (IOException e) {
            e.printStackTrace();
        }


        final Student student = new Student(sid, sname, spwd, filename, sbirthday);
        final int i = studentService.updateStudent(student);

        String message = "更改学生 " + (i > 0 ? "成功" : "失败！");

        request.setAttribute("message", message);

        return "jsp/success";
    }

    @RequestMapping("/getOneByTid.action")
    public String getOneByTid(Integer tid, Model model) {

        final Student student = studentService.getStudentById(tid);
        model.addAttribute("student", student);

        return "jsp/success";
    }

}
